﻿
using System;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Threading;
namespace DotNetFrameworkExtendClass
{
    /// <summary>
    /// 
    /// </summary>
    public static class SqlConnectionX
    {
        /// <summary>
        /// 使用现成的方式执行Open操作
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="Timeout">设置超时的时间，单位为（秒），默认3秒，支持小数位的毫秒。</param>
        public static void Open(this SqlConnection conn, double Timeout = 3.0)
        {
            conn.OpenDb(Timeout);
        }
        /// <summary>
        /// 用线程的方式执行SqlConnection.Open()
        /// </summary>
        /// <param name="conn"></param>
        /// <param name="Timeout">设置超时的时间，单位为（秒），默认3秒，支持小数位的毫秒。</param>
        public static void OpenDb(this SqlConnection conn, double Timeout = 3.0)
        {
            bool successed = false;
            var thread = new Thread(() =>
            {
                try
                {
                    if (ConnectionState.Open == conn.State)
                    {
                        successed = true;
                    }
                    else
                    {
                        conn.Open();
                        successed = true;
                    }
                }
                catch (SqlException ex)
                {
                    throw ex;
                }
                catch (ThreadAbortException)
                {
                }
            });
            thread.IsBackground = true;
            Stopwatch sw = Stopwatch.StartNew();
            thread.Start();
            TimeSpan timeout = TimeSpan.FromSeconds(Timeout);
            while (sw.Elapsed < timeout)
            {
                thread.Join(TimeSpan.FromMilliseconds(200));
            }
            sw.Stop();
            if (!successed)
            {
                throw new Exception("超时无法连接.");
            }
        }
        /// <summary>
        /// 如果数据库已经Open那么执行Close
        /// </summary>
        /// <param name="conn"></param>
        public static void CloseDb(this SqlConnection conn)
        {
            if (ConnectionState.Open == conn.State) conn.Close();
        }
    }
}
